<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>资产上报 - 资产管理系统</title>
    <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4e73df;
            --secondary-color: #f8f9fa;
            --dark-color: #343a40;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --info-color: #17a2b8;
            --light-color: #f8f9fa;
            --muted-color: #6c757d;
        }

        body {
            background-color: #f8f9fc;
            font-family: 'Inter', system-ui, sans-serif;
            font-size: 14px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .navbar {
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            padding: 0.5rem 0;
            background-color: var(--primary-color);
            transition: background-color 0.3s ease;
            width: 100%;
        }

        .navbar:hover {
            background-color: #4367d6;
        }

        .navbar-brand {
            font-weight: 600;
            font-size: 1.35rem;
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .container {
            width: 85%;
            max-width: 85%;
            padding-bottom: 1.5rem;
            flex: 1;
            margin: 0 auto;
        }

        .form-container {
            background: white;
            padding: 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
            margin-bottom: 1.5rem;
            border: 1px solid #e3e6f0;
            max-width: 800px;
            margin: 2rem auto;
        }

        h2 {
            color: var(--dark-color);
            margin: 0 0 1.5rem 0;
            padding-bottom: 0.75rem;
            border-bottom: 1px solid #e3e6f0;
            font-size: 1.4rem;
            font-weight: 600;
        }

        .form-label {
            font-weight: 500;
            margin-bottom: 0.3rem;
            font-size: 13px;
            color: #5a5c69;
        }

        .form-label.required:after {
            content: '*';
            color: var(--danger-color);
            margin-left: 4px;
        }

        .form-control,
        .form-select {
            padding: 0.375rem 0.75rem;
            border: 1px solid #d1d3e2;
            border-radius: 0.35rem;
            font-size: 13px;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: #bac8f3;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border: none;
            padding: 0.5rem 1rem;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.2s;
        }

        .btn-primary:hover {
            background-color: #3a5bc7;
        }

        .btn-animated {
            position: relative;
            overflow: hidden;
        }

        .btn-animated:after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 5px;
            height: 5px;
            background: rgba(255, 255, 255, 0.3);
            opacity: 0;
            border-radius: 100%;
            transform: scale(1, 1) translate(-50%);
            transform-origin: 50% 50%;
        }

        .btn-animated:active:after {
            animation: ripple 0.6s ease-out;
        }

        @keyframes ripple {
            0% {
                transform: scale(0, 0);
                opacity: 0.5;
            }
            100% {
                transform: scale(20, 20);
                opacity: 0;
            }
        }

        .image-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 8px;
        }

        .image-preview {
            height: 80px;
            width: auto;
            border-radius: 3px;
            border: 1px solid #eee;
            object-fit: cover;
        }

        .form-text {
            font-size: 12px;
            margin-top: 3px;
            color: var(--muted-color);
        }

        .nav-link {
            position: relative;
            overflow: hidden;
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            transition: all 0.2s ease;
        }

        .nav-link:not(.active):after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 0;
            height: 2px;
            background-color: white;
            transition: width 0.3s ease;
            border-radius: 2px;
        }

        .nav-link:not(.active):hover:after {
            width: 100%;
        }

        .nav-link.active {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .navbar-brand svg {
            transition: transform 0.3s ease;
        }

        .navbar-brand:hover svg {
            transform: scale(1.1);
        }

        .btn-outline-light {
            border-width: 1.5px;
        }

        footer {
            background-color: white;
            border-top: 1px solid #e3e6f0;
            padding: 1rem 0;
            margin-top: auto;
            width: 100%;
        }

        .footer-links {
            display: flex;
            gap: 1rem;
        }

        .footer-links a {
            color: var(--muted-color);
            transition: color 0.2s ease;
        }

        .footer-links a:hover {
            color: var(--primary-color);
            text-decoration: none;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .container {
                width: 95%;
                max-width: 95%;
                padding-left: 15px;
                padding-right: 15px;
            }

            .form-container {
                padding: 1rem;
            }

            .image-preview {
                height: 70px;
            }
        }

        @media (max-width: 576px) {
            .container {
                width: 100%;
                max-width: 100%;
            }
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container py-2">
            <!-- 品牌标识 -->
            <a class="navbar-brand" href="#">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M4 6H20V20H4V6Z" stroke="white" stroke-width="2" stroke-linecap="round"
                        stroke-linejoin="round" />
                    <path d="M4 10H20" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    <path d="M8 6V2" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    <path d="M16 6V2" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                </svg>
                资产管理系统
            </a>

            <!-- 移动端菜单按钮 -->
            <button class="navbar-toggler py-1" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                style="border-color: rgba(255,255,255,0.3);">
                <span class="navbar-toggler-icon"></span>
            </button>

            <!-- 菜单内容 -->
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto align-items-center gap-1">
                    <li class="nav-item">
                        <a class="nav-link" href="/dashboard">
                            <i class="fa fa-dashboard mr-1"></i> 首页
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/report">
                            <i class="fa fa-plus-circle mr-1"></i> 资产上报
                        </a>
                    </li>
                </ul>

                <div class="d-flex align-items-center">
                    <a href="/logout"
                        class="btn btn-outline-light btn-sm rounded-pill px-4 py-1.5">
                        <i class="fa fa-sign-out mr-1"></i> 退出
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="form-container">
            <h2><i class="fa fa-plus-circle mr-2"></i>资产上报</h2>
            <form id="reportForm" enctype="multipart/form-data">
                <!-- 资产基本信息 -->
                <div class="row g-2">
                    <div class="col-md-12">
                        <label for="asset_name" class="form-label required">资产名称</label>
                        <input type="text" class="form-control" id="asset_name" required placeholder="请输入资产名称">
                    </div>
                </div>

                <div class="row g-2 mt-2">
                    <div class="col-md-6">
                        <label for="category_main" class="form-label required">大类</label>
                        <select class="form-select" id="category_main" required>
                            <option value="">加载分类中...</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label for="category_sub" class="form-label required">小类</label>
                        <input type="text" class="form-control" id="category_sub" required placeholder="请输入小类">
                    </div>
                </div>

                <div class="row g-2 mt-2">
                    <div class="col-md-4">
                        <label for="unit" class="form-label required">单位</label>
                        <select class="form-select" id="unit" required>
                            <option value="">加载单位中...</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="value" class="form-label required">价值</label>
                        <input type="number" class="form-control" id="value" min="0" step="0.01" required
                            placeholder="资产价值">
                    </div>
                    <div class="col-md-4">
                        <label for="status" class="form-label required">状态</label>
                        <select class="form-select" id="status" required>
                            <option value="">加载状态中...</option>
                        </select>
                    </div>
                </div>

                <!-- 资产位置信息 -->
                <div class="row g-2 mt-2">
                    <div class="col-md-6">
                        <label for="department" class="form-label required">所属部门</label>
                        <input type="text" class="form-control" id="department" required placeholder="请输入所属部门">
                    </div>
                    <div class="col-md-6">
                        <label for="location" class="form-label required">存放位置</label>
                        <input type="text" class="form-control" id="location" required placeholder="请输入具体存放位置">
                    </div>
                </div>

                <!-- 资产详细信息 -->
                <div class="row g-2 mt-2">
                    <div class="col-md-4">
                        <label for="service_life" class="form-label">使用年限(年)</label>
                        <input type="number" class="form-control" id="service_life" min="1" placeholder="预计使用年限">
                    </div>
                    <div class="col-md-4">
                        <label for="depreciation_rate" class="form-label">折旧率(%)</label>
                        <input type="number" class="form-control" id="depreciation_rate" min="0" max="100" step="0.1"
                            placeholder="年折旧率">
                    </div>
                    <div class="col-md-4">
                        <label for="purchase_date" class="form-label">购买日期</label>
                        <input type="date" class="form-control" id="purchase_date">
                    </div>
                </div>

                <div class="row g-2 mt-2">
                    <div class="col-md-6">
                        <label for="manufacturer" class="form-label">生产厂商</label>
                        <input type="text" class="form-control" id="manufacturer" placeholder="生产厂商名称">
                    </div>
                    <div class="col-md-6">
                        <label for="model" class="form-label">型号</label>
                        <input type="text" class="form-control" id="model" placeholder="资产型号">
                    </div>
                </div>

                <div class="mb-3 mt-2">
                    <label for="description" class="form-label">详细描述</label>
                    <textarea class="form-control" id="description" rows="2" placeholder="资产详细描述、备注信息等"></textarea>
                </div>

                <div class="mb-3">
                    <label for="images" class="form-label">上传图片 (最多3张，每张不超过1MB)</label>
                    <input type="file" class="form-control" id="images" multiple accept="image/*">
                    <div class="form-text">支持JPEG, PNG, GIF格式</div>
                    <div class="image-preview-container" id="imagePreview"></div>
                </div>

                <div class="d-grid gap-2 mt-3">
                    <button type="submit" class="btn btn-primary btn-animated">
                        <i class="fa fa-save mr-2"></i>提交
                    </button>
                </div>
            </form>
        </div>
    </div>

    <footer class="mt-auto py-3">
        <div class="container">
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-center">
                <p class="text-sm text-muted mb-2 mb-md-0">© 2025 资产管理系统. TIMI开发.</p>
                <div class="footer-links">
                    <a href="#" class="text-muted">
                        <i class="fa fa-question-circle mr-1"></i> 帮助中心
                    </a>
                    <a href="#" class="text-muted">
                        <i class="fa fa-file-text-o mr-1"></i> 使用手册
                    </a>
                    <a href="#" class="text-muted">
                        <i class="fa fa-envelope-o mr-1"></i> 联系我们
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script src="/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局配置数据
        const appConfig = {
            categories: [],
            subCategories: {},
            units: [],
            statuses: []
        };

        // DOM加载完成后初始化
        document.addEventListener('DOMContentLoaded', async function () {
            try {
                // 加载配置文件
                await loadConfigData();

                // 初始化下拉菜单
                initDropdown('category_main', '请选择主分类', appConfig.categories);
                initDropdown('unit', '请选择单位', appConfig.units);
                initDropdown('status', '请选择状态', appConfig.statuses);

                // 设置事件监听
                setupEventListeners();

            } catch (error) {
                console.error('初始化失败:', error);
                showAlert('danger', '系统初始化失败，请刷新页面重试');
            }
        });

        // 加载配置文件
        async function loadConfigData() {
            try {
                const response = await fetch('/config.json');
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                const config = await response.json();

                // 验证配置数据
                if (!config.categories || !config.subCategories || !config.units || !config.statuses) {
                    throw new Error('配置文件格式不正确');
                }

                // 更新全局配置
                appConfig.categories = config.categories;
                appConfig.subCategories = config.subCategories;
                appConfig.units = config.units;
                appConfig.statuses = config.statuses;

            } catch (error) {
                console.error('加载配置文件失败:', error);
                throw error; // 重新抛出以便外部捕获
            }
        }

        // 初始化下拉菜单
        function initDropdown(elementId, placeholder, options) {
            const select = document.getElementById(elementId);

            // 清空现有选项
            select.innerHTML = '';

            // 添加占位选项
            const placeholderOption = document.createElement('option');
            placeholderOption.value = '';
            placeholderOption.textContent = placeholder;
            placeholderOption.disabled = true;
            placeholderOption.selected = true;
            select.appendChild(placeholderOption);

            // 添加数据选项
            options.forEach(option => {
                const optionElement = document.createElement('option');
                optionElement.value = option;
                optionElement.textContent = option;
                select.appendChild(optionElement);
            });

            // 如果是主分类，启用选择
            if (elementId === 'category_main') {
                select.disabled = false;
            }
        }

        // 设置事件监听
        function setupEventListeners() {
            // 主分类变更事件
            document.getElementById('category_main').addEventListener('change', function () {
                // const mainCategory = this.value;
                // const subSelect = document.getElementById('category_sub');

                // // 重置子分类
                // subSelect.innerHTML = '';
                // const placeholderOption = document.createElement('option');
                // placeholderOption.value = '';
                // placeholderOption.textContent = '请选择子分类';
                // placeholderOption.disabled = true;
                // placeholderOption.selected = true;
                // subSelect.appendChild(placeholderOption);

                // // 如果有子分类则加载
                // if (mainCategory && appConfig.subCategories[mainCategory]) {
                //     appConfig.subCategories[mainCategory].forEach(subCat => {
                //         const option = document.createElement('option');
                //         option.value = subCat;
                //         option.textContent = subCat;
                //         subSelect.appendChild(option);
                //     });
                //     subSelect.disabled = false;
                // } else {
                //     subSelect.disabled = true;
                // }
            });

            // 表单提交事件
            document.getElementById('reportForm').addEventListener('submit', async function (e) {
                e.preventDefault();

                // 验证表单
                if (!validateForm()) {
                    return;
                }

                // 准备提交数据
                const formData = new FormData();
                formData.append('asset_name', document.getElementById('asset_name').value);
                formData.append('category_main', document.getElementById('category_main').value);
                formData.append('category_sub', document.getElementById('category_sub').value);
                formData.append('unit', document.getElementById('unit').value);
                formData.append('value', document.getElementById('value').value);
                formData.append('status', document.getElementById('status').value);
                formData.append('department', document.getElementById('department').value);
                formData.append('location', document.getElementById('location').value);

                // 可选字段
                const serviceLife = document.getElementById('service_life').value;
                if (serviceLife) formData.append('service_life', serviceLife);

                const depreciationRate = document.getElementById('depreciation_rate').value;
                if (depreciationRate) formData.append('depreciation_rate', depreciationRate);

                const purchaseDate = document.getElementById('purchase_date').value;
                if (purchaseDate) formData.append('purchase_date', purchaseDate);

                const manufacturer = document.getElementById('manufacturer').value;
                if (manufacturer) formData.append('manufacturer', manufacturer);

                const model = document.getElementById('model').value;
                if (model) formData.append('model', model);

                const description = document.getElementById('description').value;
                if (description) formData.append('description', description);

                // 图片文件
                const files = document.getElementById('images').files;
                for (let i = 0; i < files.length; i++) {
                    formData.append('images', files[i]);
                }

                // 提交表单
                await submitForm(formData);
            });
        }

        // 表单验证
        function validateForm() {
            const requiredFields = [
                'asset_name', 'category_main', 'unit', 'value', 'status', 'department', 'location'
            ];

            for (const fieldId of requiredFields) {
                const field = document.getElementById(fieldId);
                if (!field.value.trim()) {
                    showAlert('warning', `请填写${field.labels[0].textContent}`);
                    field.focus();
                    return false;
                }
            }

            // 验证价值是否为有效数字
            const value = parseFloat(document.getElementById('value').value);
            if (isNaN(value) || value <= 0) {
                showAlert('warning', '请输入有效的资产价值');
                document.getElementById('value').focus();
                return false;
            }

            return true;
        }

        // 提交表单
        async function submitForm(formData) {
            const submitBtn = document.querySelector('#reportForm button[type="submit"]');

            try {
                // 显示加载状态
                submitBtn.disabled = true;
                submitBtn.innerHTML = `
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    提交中...
                `;

                // 发送请求
                const response = await fetch('/api/reports', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '服务器返回错误');
                }

                // 提交成功
                showAlert('success', '资产上报成功！');
                setTimeout(() => {
                    window.location.href = '/dashboard';
                }, 1500);

            } catch (error) {
                console.error('提交失败:', error);
                showAlert('danger', `上报失败: ${error.message}`);
            } finally {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa fa-save mr-2"></i>提交';
            }
        }

        // 显示提示信息
        function showAlert(type, message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.role = 'alert';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;

            const container = document.querySelector('.form-container');
            container.prepend(alertDiv);

            // 5秒后自动消失
            setTimeout(() => {
                alertDiv.classList.remove('show');
                setTimeout(() => alertDiv.remove(), 150);
            }, 5000);
        }

        // 图片预览功能
        document.getElementById('images').addEventListener('change', function (e) {
            const previewContainer = document.getElementById('imagePreview');
            previewContainer.innerHTML = '';

            if (this.files.length > 3) {
                showAlert('warning', '最多只能上传3张图片');
                this.value = '';
                return;
            }

            for (let i = 0; i < this.files.length; i++) {
                const file = this.files[i];
                if (file.size > 1024 * 1024) {
                    showAlert('warning', '图片大小不能超过1MB');
                    this.value = '';
                    previewContainer.innerHTML = '';
                    return;
                }

                const reader = new FileReader();
                reader.onload = function (e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.className = 'image-preview';
                    previewContainer.appendChild(img);
                }
                reader.readAsDataURL(file);
            }
        });
    </script>
</body>

</html>